/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.web;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import com.rrx360.common.exception.RException;
import com.rrx360.common.exception.UserException;
import com.rrx360.common.exception.ValidateException;
import com.rrx360.common.pagequery.FieldEntry;
import com.rrx360.common.pagequery.PageQueryCondition;
import com.rrx360.common.result.UserRstCode;
import com.rrx360.common.util.JsonUtil;
import com.rrx360.common.web.bean.RxResult;

@Controller
public class BaseWebController extends BaseController {

  private static final String ORDER_PREFIX = "_order_";

  protected String exceptionPage = "common/errors/exception";

  protected PageQueryCondition fillConditionByRequest(HttpServletRequest request,
      PageQueryCondition condition) {
    return fillConditionByRequest(request, condition, null, null);
  }

  protected PageQueryCondition fillConditionByRequest(HttpServletRequest request,
      PageQueryCondition condition, String[] conditionFields, String[] sortFields) {
    Enumeration<String> names = request.getParameterNames();
    Set<String> conditionFieldSet = null;
    if (conditionFields != null) {
      conditionFieldSet = new HashSet<>();
      for (String s : conditionFields) {
        conditionFieldSet.add(s);
      }
    }

    if (sortFields != null) {
      if (conditionFieldSet == null) {
        conditionFieldSet = new HashSet<>();
      }
      for (String s : sortFields) {
        conditionFieldSet.add(ORDER_PREFIX + s);
      }
    }

    while (names.hasMoreElements()) {
      String name = names.nextElement();
      if (conditionFieldSet != null && !conditionFieldSet.contains(name)) {
        continue;
      }
      // except pageIndex,pageSize and randomData '_'
      if ("pageIndex".equals(name) || "pageSize".equals(name) || "_".equals(name)) {
        continue;
      }
      if (name.startsWith(ORDER_PREFIX)) {
        String value = request.getParameter(name);
        name = name.substring(ORDER_PREFIX.length());
        String[] values = value.split("_");
        condition.addSortField(name, Long.parseLong(values[0]), values[1]);
        continue;

      }
      String[] values = request.getParameterValues(name);
      if (values.length == 1) {
        condition.putField(new FieldEntry(name, values[0]));
      } else if (values.length > 1) {
        condition.putField(new FieldEntry(name, values));
      }
    }
    if (condition.getSortList() != null) {
      Collections.sort(condition.getSortList());
      Collections.reverse(condition.getSortList());
    }
    return condition;
  }



  @ExceptionHandler
  @ResponseBody
  public ModelAndView exception(Throwable e, HandlerMethod handlerMethod,
      HttpServletResponse response) {
    exceptionDo(e);// 告警异常处理
    ModelAndView mav = new ModelAndView();
    ResponseBody rb = handlerMethod.getMethodAnnotation(ResponseBody.class);
    String rstCode = null;
    String rstInfo = null;
    if (e instanceof RException) {
      if (logger.isDebugEnabled()) {
        logger.error(e.getMessage(), e);
      }
      RException re = (RException) e;
      rstCode = re.getCode();
      if (re.getCode() == null) {
        rstCode = UserRstCode.EXCEPTION;
      }
      rstInfo = re.getInfo();
      logger.info("code:" + rstCode + " info:" + re.getInfo());
      if (!(e instanceof UserException)) {
        rstCode = UserRstCode.EXCEPTION;
        rstInfo = "处理异常";
      }
    } else {
      rstCode = UserRstCode.EXCEPTION;
      rstInfo = "处理异常";
      logger.error(e.getMessage(), e);
    }

    if (rb != null) {
      RxResult result = new RxResult();
      result.setRstCode(rstCode);
      result.setRstInfo(rstInfo);
      if (e instanceof ValidateException) {
        ValidateException ve = (ValidateException) e;
        logger.info(ve.getFieldName() + " " + ve.getInfo());
        result.addError(ve.getFieldName(), ve.getInfo());
      }
      response.setContentType("application/json;charset=UTF-8");
      try {
        response.getOutputStream()
            .write(JsonUtil.toJsonString(result).getBytes(Charset.defaultCharset()));
      } catch (IOException e1) {
        logger.error(e.getMessage(), e);
      }
    } else {
      response.reset();
      mav.setViewName(exceptionPage);
    }

    return mav;
  }

  public static void exceptionDo(Throwable e) {
    if (!(e instanceof UserException) && !(e instanceof ValidateException)) {
//      AlertUtil.alert(e);
    }
  }
}
